#####################
# run2.py - 27 feb 2012 - Hessel van der Molen
# Runs & tests 2 identical self-learning agents in the domination-game
#   each 5 runs of a game, the cumaltive scores are compared. 
#      The Q-table with the agent of the higest score is inserted in both agents
#####
# USAGE:
# 
# shell> python run.py [elements]
# [elements] is:
# -r <agent.py>             (               default: agent3.py)
# -n <numberOfRoundsToPlay> (integer        default: 1) --> In chunks of 5 games!
# -s <stepPerGame>          (integer        default: 600)
# -t <ThinkTimeAgent>       (float(seconds) default: 0.1 seconds)

# enable to run code in map-structure:
import os, sys, time
path, filename = os.path.split("../Domination-Game/domination")
sys.path.append(path)
defaultAgent = '../Domination-Game/domination/agent.py'

#code to run game
from domination import core, run
import cPickle

#default values
redAgent = 'agent3.py'
blueAgent = 'agent3.py'
iterations = 1
max_steps = 600
think_time = 0.1

GAMESPERROUND = 2

arguments = len(sys.argv) - 1
if (arguments%2 == 1):
    print "ERROR not an even number of arguments given"
    print str(len(sys.argv)) + " " + str(sys.argv)
else:
    # set commands
    for i in range(arguments/2):
        cmd = sys.argv[i*2+1]
        val = sys.argv[i*2+2]

        if (cmd == '-r'): #red agend
            redAgent = val
            blueAgent = val
        elif (cmd == '-n'): #number of iterations
            iterations = int(val)
        elif (cmd == '-s'): # number of steps per game
            max_steps = int(val)
        elif (cmd == '-t'): # think time of agent
            think_time = float(val)
        else: # not recognised
            print "Incorrect Command: " + cmd
    
    # Define settings
    settings = core.Settings(max_steps=max_steps, think_time=think_time)

    # list for keeping track of all scores
    
    # Run game(s)
    start = time.time()
    for a in range(iterations):
  
        score = []      
        for b in range(GAMESPERROUND):
            #run game
            print 'Iteration: #' + str(a+1) + " game#: "  + str(b+1)
            game = core.Game(redAgent, blueAgent, record=False, rendered=False, settings=settings)
            game.run()
            score.append(game.score_red)

        #calculate avg score:
        avg = 0
        for i in score:
            avg += i
        avg = avg/GAMESPERROUND
        
        # evaluate score
        if avg > 500: #red wins
            print "RED WINS: " + str(avg)
            file0 = open('Qtable_agent3_0.txt','r')
            file1 = open('Qtable_agent3_1.txt','w')
            Qtable = cPickle.load(file0)
            cPickle.dump(Qtable, file1)
            file0.close()
            file1.close()
        else: # blue wins
            print "BLUE WINS: " + str(1000 - avg)
            file0 = open('Qtable_agent3_0.txt','w')
            file1 = open('Qtable_agent3_1.txt','r')
            Qtable = cPickle.load(file1)
            cPickle.dump(Qtable, file0)
            file0.close()
            file1.close()        
       
    end = time.time()
    duration = str(int(end-start))
    print('the duration was: '+duration+' seconds')
